<?php

class Friend extends ActiveRecordBase
{
	public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

	public function tableName() {
		return "{{friends}}";
	}

	public function relations() {
		return array(
			'user' => array(self::HAS_ONE, 'User', 'user_id'),
			'friend' => array(self::HAS_ONE, 'User', array('friend_id' => 'user_id')),
		);
	}

	public function rules()
	{
	}

	public function beforeSave() {
		if ( parent::beforeSave() && empty($this->timestamp) ) {
			$this->timestamp = parseDate($this->timestamp);
		}

		return true;
	}
	
	public static function makeFriend($user_id, $friend_id) {
		// add friend
		$command = app()->db->createCommand("REPLACE INTO {{friends}} (user_id, friend_id) VALUES (:user_id, :friend_id)");
		
		$command->execute(array(
			':user_id' => $user_id,
			':friend_id' => $friend_id,
		));
		$command->execute(array(
			':user_id' => $friend_id,
			':friend_id' => $user_id,
		));

		// delete friend reqeusts
		$command = app()->db->createCommand("DELETE FROM {{friend_requests}} WHERE from_user_id=:user_id AND to_user_id=:friend_id");
		$command->execute(array(
			':user_id' => $user_id,
			':friend_id' => $friend_id,
		));
		$command->execute(array(
			':user_id' => $friend_id,
			':friend_id' => $user_id,
		));
	}
	
	public static function isFriend($user_id, $friend_id) {
		
		$model = Friend::model()->findByAttributes(array(
			'user_id' => $user_id,
			'friend_id' => $friend_id,
		));
		
		return !empty($model) ? true : false;
		
	}

	public static function findFriends($user_id, $params = array(), $number = 20, $page = 1) 
	{
		$command = app()->db->createCommand();
		$command->from('tbl_users u')
				->leftJoin('tbl_friends f1', 'u.user_id = f1.user_id')
				->leftJoin('tbl_friends f2', 'f1.friend_id = f2.friend_id')				
				->leftJoin('tbl_users u1', "f2.user_id = u1.user_id AND u1.status = 'A'")
				->leftJoin('tbl_users u2', "f2.friend_id = u2.user_id AND u2.status = 'A'")
				->where('f2.user_id = :user_id AND f1.user_id != :user_id')
				->group('u.user_id, f1.user_id')
				->offset(($page - 1) * $number)
				->limit($number);

		$select = array(
			'u.name',
			'IF(u.user_id, u.user_id, f2.user_id) AS user_id',
			'SUM(IF(f2.user_id=:user_id, 1, 0)) AS mutual_friends_count',
			'GROUP_CONCAT(u2.name) AS mutual_friends',
			'GROUP_CONCAT(u2.seo_name) AS mutual_friend_seo_names',
		);
		
		$order = array();
		
		$data = array(
			':user_id' => $user_id,
		);
		
		$conditions = array('or');
		//Fix param
		$params['name'] = empty($params['name']) ? " " : $params['name'];
		$params['email'] = empty($params['email']) ? " " : $params['email'];
		$params['phone'] = empty($params['phone']) ? " " : $params['phone'];
		
		if ( !empty($params['name']) ) {
			$params['name'] = str_replace("'", "", $params['name']);
			$select[] = sprintf("u.name LIKE '%%%s%%' AS name_relevance", $params['name']);
			$conditions[] = array('and', 'u.user_id!=:user_id', array('like', 'u.name', sprintf('%%%s%%', $params['name'])));
			$order[] = sprintf("(`u`.`name` LIKE '%%%s%%') DESC", $params['name']);
		}
		
		if ( !empty($params['email']) ) {
			$params['email'] = str_replace("'", "", $params['email']);
			$select[] = sprintf("u.email LIKE '%%%s%%'  AS email_relevance", $params['email']);
			$conditions[] = array('and', 'u.user_id!=:user_id', array('like', 'u.email', sprintf('%%%s%%', $params['email'])));
			$order[] = sprintf("(`u`.`email` LIKE '%%%s%%') DESC", $params['email']);
//			$conditions[] = array('and', 'u.user_id!=:user_id', array('like', 'u.email', sprintf('%%%s%%', $params['email'])));
		}
		
		if ( !empty($params['phone']) ) {
			$params['phone'] = str_replace("'", "", $params['phone']);
			$select[] = sprintf("u.phone LIKE '%%%s%%'  AS phone_relevance", $params['phone']);
			$conditions[] = array('and', 'u.user_id!=:user_id', array('like', 'u.phone', sprintf('%%%s%%', $params['phone'])));
			$order[] = sprintf("(`u`.`phone` LIKE '%%%s%%') DESC", $params['phone']);
//			$conditions[] = array('and', 'u.user_id!=:user_id', array('like', 'u.phone', sprintf('%%%s%%', $params['phone'])));
		}
		
		// friends of friends
		$conditions[] = array('and', 'f2.user_id=:user_id', 'f1.user_id!=:user_id');

		$conditions = array('and', "u.status='A'", "u.user_type='C'", $conditions);
		
		$order[] = 'mutual_friends_count DESC';
		$order[] = 'u.name ASC';
		
		// build command
		$command->select($select)
				->where($conditions)
				->order($order);

		$suggested = $command->queryAll(true, $data);
		
		return $suggested;

	}
}